package pe.edu.upc.dsd.l33t.dao.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

import pe.edu.upc.dsd.l33t.dao.PagoDao;
import pe.edu.upc.dsd.l33t.model.Pago;

@Repository
public class PagoDaoJdbc extends SimpleJdbcDaoSupport implements PagoDao {

	@Autowired
	public PagoDaoJdbc(DataSource dataSource) {
		setDataSource(dataSource);
	}
	
	@Override
	public Pago find(String numeroTransaccion) {

		try {
			return getSimpleJdbcTemplate()
					.queryForObject(
							"select transactionNumber, total, transactionDate, status, creditCardNumber from pago where transactionNumber=?",
							new BeanPropertyRowMapper<Pago>(Pago.class),
							numeroTransaccion);
		} catch (EmptyResultDataAccessException e) {
			System.out.println(e.getMessage());
			return null;
		}
	}

	@Override
	public void save(Pago pago) {

		getSimpleJdbcTemplate()
		.update("insert into pago(transactionNumber, total, transactionDate, status, creditCardNumber) values (?, ?, ?, ?, ?)",
				pago.getTransactionNumber(), pago.getTotal(),
				pago.getTransactionDate(), pago.getStatus(), pago.getCreditCardNumber());
	}

	@Override
	public long getMax() {

		return getSimpleJdbcTemplate().queryForLong(
						"select max(transactionNumber) from pago");
	}
	
}
